package cn.maihe.elg.operation.web.guarantee;

import cn.maihe.elg.operation.exception.ErrorCode;
import cn.maihe.elg.operation.exception.SystemRuntimeException;
import cn.maihe.elg.operation.model.enums.UserType;
import cn.maihe.elg.operation.repository.entity.GuaranteeDO;
import cn.maihe.elg.operation.repository.entity.GuaranteeVo;
import cn.maihe.elg.operation.security.model.UserContext;
import cn.maihe.elg.operation.service.guarantee.GuaranteeService;
import cn.maihe.elg.operation.supports.system.ElgResourceService;
import cn.maihe.elg.operation.utils.UserContextUtil;
import cn.maihe.framework.starter.base.sql.PageBo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * @Description 保函电子文件controller
 * @Author caixh
 * @Date 2021/4/14.
 */
@Api(value = "保函电子文件管理", tags = "保函电子文件管理")
@RestController
@RequestMapping("/api")
@Slf4j
public class GuaranteeController {
    @Resource
    private GuaranteeService guaranteeService;
    @Resource
    private ElgResourceService elgResourceService;

    @ApiOperation(value = "分页查询保函电子模板", notes = "根据保函电子模板类型、机构编码、机构名称 分页查询")
    @RequestMapping(value = "/guarantees", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNo", value = "页数", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页大小", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "sectionName", value = "标段名称", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "guaranteeStatus", value = "保函状态", dataType = "String", paramType = "query"),
//            @ApiImplicitParam(name = "Name", value = "保函电子模板名称", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "gmtCreateRange", value = "创建时间（startDate,endDate）", dataType = "String", paramType = "query")
    })
    public PageBo<GuaranteeDO> pageList(int pageNo, int pageSize, String gmtCreateRange, GuaranteeVo vo) {
        //登录机构过滤
        UserContext uc= UserContextUtil.getUserContext();
        if(UserType.GENERAL.getType() != uc.getUserType()){
            vo.setOrgId(uc.getOrgId());
        }
        return guaranteeService.selectPageBySql(pageNo, pageSize, gmtCreateRange, vo);
    }

    @ApiOperation(value = "获取保函电子模板", notes = "根据保函电子模板id获取保函电子模板")
    @ApiImplicitParam(name = "id", value = "保函电子模板id", dataType = "long", paramType = "path", required = true)
    @RequestMapping(value = "/guarantee/{id}", method = RequestMethod.GET)
    public GuaranteeDO get(@PathVariable Long id) {
        GuaranteeDO curDO = guaranteeService.selectById(id);
        if (curDO == null) {
            throw new SystemRuntimeException(ErrorCode.NOTEXISTS, "保函电子模板id");
        }
        return curDO;
    }

    @ApiOperation(value = "保函电子下载", notes = "根据保函id下载保函")
    @RequestMapping(value = "/guarantee/download", method = RequestMethod.POST)
    public String download(@Validated @RequestBody GuaranteeVo vo, HttpServletResponse response) throws UnsupportedEncodingException {
        GuaranteeDO mDO = guaranteeService.selectById(vo.getId());

        String content = mDO.getGuaranteeFile();
        response.setContentType("application/octet-stream");

        File file = elgResourceService.getFileByRelativePath(mDO.getGuaranteeFile());
        if(!file.exists()){
            return "下载文件不存在";
        }
        response.setCharacterEncoding("utf-8");
        response.setContentLength((int) file.length());
        response.setHeader("Content-Disposition", "attachment; fileName="+  file.getName() +";filename*=utf-8''"+ URLEncoder.encode(file.getName(),"UTF-8") );
        //解决文件名中文问题

        try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {
            byte[] buff = new byte[1024];
            OutputStream os  = response.getOutputStream();
            int i = 0;
            while ((i = bis.read(buff)) != -1) {
                os.write(buff, 0, i);
                os.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
            return "下载失败";
        }
        return "下载成功";
    }



}
